package br.com.sgmf.service;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.com.sgmf.dao.NotaFiscalDAO;
import br.com.sgmf.dao.PecaDAO;
import br.com.sgmf.model.Fornecedor;
import br.com.sgmf.model.ItemNota;
import br.com.sgmf.model.NotaFiscal;
import br.com.sgmf.model.Peca;

@Service
public class NotaFiscalService {

	@Autowired
	NotaFiscalDAO notaFiscalDAO;

	@Autowired
	PecaDAO pecaDAO;

	public void save(NotaFiscal notaFiscal, Fornecedor fornecedor,
			Collection<ItemNota> itensNota) {
		notaFiscal.setFornecedor(fornecedor);
		notaFiscal.setItensNota(itensNota);
		if (notaFiscal.getId() == null) {
			notaFiscalDAO.save(notaFiscal);
		} else {
			notaFiscalDAO.update(notaFiscal);
		}
		// FIXME: alteração na quantidade de peças
		if (CollectionUtils.isNotEmpty(notaFiscal.getItensNota())) {
			for (ItemNota itemNota : itensNota) {
				Peca peca = itemNota.getPeca();
				peca.somarQuantidade(itemNota.getQuantidade());
				pecaDAO.update(peca);
			}
		}
	}

	public void delete(NotaFiscal notaFiscal) {
		notaFiscalDAO.delete(notaFiscal);
	}

	public List<NotaFiscal> findAll() {
		return notaFiscalDAO.findAll();
	}

	public List<NotaFiscal> findBetweenDate(Date inicio, Date fim) {
		return notaFiscalDAO.findBetweenDate(inicio, fim);
	}

}
